

const userList = []


// socket登录接口
const loginApi = {
  // 登录
  login({userName}){
    let id = this.id
    let idx = userList.findIndex(item => item.userName === userName)

    if (idx < 0) {
      userList.push({userName,userId:id})
    } else {
      userList[idx].userId = id
    }

    this.broadcast.emit('system',{userName},'login')
    let list = [...userList].filter(i => i.userId !== id)
    this.emit('system',{userList:list},'userlist')
  },
  logout(data){

  },
  disconnect(reason){
    let id = this.id
    console.log('断开连接',id);
    let idx = userList.findIndex(i => i.userId === id)
    if (idx > 0){
      userList.splice(idx,1)
    }
  }
}


// webRTC信令服务
const WebRtcApi = {
  offer({userName, offerName, offer}){
    this.broadcast.emit('system',{userName, offerName, offer},'offer')
  },
  answer({userName,answer}){
    this.broadcast.emit('system',{userName,answer},'answer')
  },
  candidate({userName,candidate}){
    this.broadcast.emit('system',{userName,candidate},'candidate')
  }
}










const events = Object.assign({},
  loginApi,
  WebRtcApi
)



const getMessage = (socket) => {
  for (const key in events) {
    socket.on(key,events[key])
  }

}


module.exports = getMessage